package com.scpii.universal.service.impl;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.xwork.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.doone.comm.util.StringUtil;
import com.google.protobuf.InvalidProtocolBufferException;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.PageNavigationIconDto;
import com.scpii.universal.hibernate.dao.AppDao;
import com.scpii.universal.hibernate.dao.AppIconDao;
import com.scpii.universal.hibernate.dao.AppStyleImgDao;
import com.scpii.universal.hibernate.dao.AppUpdateDao;
import com.scpii.universal.hibernate.dao.PageNavigationIconDao;
import com.scpii.universal.hibernate.entity.AppIconTab;
import com.scpii.universal.hibernate.entity.AppStyleImgTab;
import com.scpii.universal.hibernate.entity.AppTab;
import com.scpii.universal.hibernate.entity.AppUpdateTab;
import com.scpii.universal.pb.UniversalProtocol.BuildAppConfigs;
import com.scpii.universal.pb.UniversalProtocol.Cmd;
import com.scpii.universal.pb.UniversalProtocol.CreatComplieTaskCS;
import com.scpii.universal.pb.UniversalProtocol.CreatComplieTaskSC;
import com.scpii.universal.pb.UniversalProtocol.DownLoadPicInfo;
import com.scpii.universal.pb.UniversalProtocol.GetPackInfoSC;
import com.scpii.universal.pb.UniversalProtocol.GuideBarInfo;
import com.scpii.universal.pb.UniversalProtocol.IniCoreInfo;
import com.scpii.universal.pb.UniversalProtocol.PageInfo;
import com.scpii.universal.pb.UniversalProtocol.QryFinishComplieTaskCS;
import com.scpii.universal.pb.UniversalProtocol.QryFinishComplieTaskSC;
import com.scpii.universal.pns.dao.AppConfigsDao;
import com.scpii.universal.pns.entity.AppConfigs;
import com.scpii.universal.service.PbInterfaceService;
import com.scpii.universal.util.Conversion;
import com.scpii.universal.util.EhCacheManager;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

@Service
public class PbInterfaceServiceImpl implements PbInterfaceService {

	@Resource
	private AppUpdateDao appUpdateDao;

	@Resource
	private AppDao appDao;

	@Resource
	private PageNavigationIconDao pageNavigationIconDao;

	@Resource
	private AppIconDao appIconDao;

	@Resource
	private AppStyleImgDao appStyleImgDao;

	@Resource
	private AppConfigsDao appConfigsDao;

	private static final String APP_LOGO_NAME = "icon.png";
	private static final String APP_BK_IMG_NAME = "background.png";
	private static final String TITLE_BK_IMG_NAME = "bg_titlebar.png";
	private static final String NAV_BK_IMG_NAME = "bg_tabbar.png";
	private static final String NAV_ICON_BK_IMG_NAME = "tab_press_bg.png";
	private static final String TITLE_BK_IMG_HOME_NAME = "bg_titlebar_sub.png";
	private static final String LIST_BK_IMG_NAME = "bg_list.png";

	public void setAppUpdateDao(AppUpdateDao appUpdateDao) {
		this.appUpdateDao = appUpdateDao;
	}

	public void setAppDao(AppDao appDao) {
		this.appDao = appDao;
	}

	public void setPageNavigationIconDao(
			PageNavigationIconDao pageNavigationIconDao) {
		this.pageNavigationIconDao = pageNavigationIconDao;
	}

	public void setAppIconDao(AppIconDao appIconDao) {
		this.appIconDao = appIconDao;
	}

	public void setAppStyleImgDao(AppStyleImgDao appStyleImgDao) {
		this.appStyleImgDao = appStyleImgDao;
	}

	public void setAppConfigsDao(AppConfigsDao appConfigsDao) {
		this.appConfigsDao = appConfigsDao;
	}

	private static final Logger log = LoggerFactory
			.getLogger(PbInterfaceServiceImpl.class);

	@Override
	public byte[] getPackInfoService(Integer appUpdateId) {
		log.info("开始获取打包信息");
		GetPackInfoSC.Builder builder = GetPackInfoSC.newBuilder();
		IniCoreInfo.Builder iniCoreInfoBuilder = IniCoreInfo.newBuilder();
		GuideBarInfo.Builder guideBarInfoBuilder = GuideBarInfo.newBuilder();
		log.info("appUpdateId:" + appUpdateId);

		String serverUrl = EhCacheManager.getObject(
				GenericConstants.SERVER_URL_PREFIX).toString();
		AppUpdateTab appUpdateTab = appUpdateDao.get(appUpdateId);
		int appId = appUpdateTab.getIntAppId();
		log.info("appId:" + appId);
		AppTab appTab = appDao.get(appId);
		int enterpId = appTab.getIntEnterpId();
		int osType = appUpdateTab.getIntAppOsType();
		double appVersion = appUpdateTab.getDobAppVersion();
		int loadingIconId = appUpdateTab.getIntLoadingIconId();
		log.info("enterpId:" + enterpId + ",osType:" + osType + ",appVersion:"
				+ appVersion);

		AppIconTab loadingIcon = appIconDao.get(loadingIconId);
		DownLoadPicInfo.Builder loadingIconInfo = DownLoadPicInfo.newBuilder();
		String loadingUrl = loadingIcon.getVarIconUrl();
		loadingUrl = loadingUrl == null ? "" : serverUrl + loadingUrl;
		if (osType == GenericConstants.OPERATION_SYS_ANDROID) {
			loadingIconInfo.setPicName("splash.png");
			loadingIconInfo.setPicUrl(loadingUrl);
		} else {
			loadingIconInfo.setPicName("Default.png");
			loadingIconInfo.setPicUrl(loadingUrl);
		}
		// app logo
		AppIconTab appLogo = appIconDao.get(appUpdateTab.getIntIconId());
		DownLoadPicInfo.Builder logoInfo = DownLoadPicInfo.newBuilder();
		logoInfo.setPicName(APP_LOGO_NAME);
		logoInfo.setPicUrl(appLogo.getVarIconUrl() == null ? null : serverUrl
				+ appLogo.getVarIconUrl());

		// app style
		int styleId = appDao.get(appUpdateTab.getIntAppId()).getIntAppStyleId();
		DownLoadPicInfo.Builder appBkInfo = DownLoadPicInfo.newBuilder();
		DownLoadPicInfo.Builder titleBkInfo = DownLoadPicInfo.newBuilder();
		DownLoadPicInfo.Builder navBkInfo = DownLoadPicInfo.newBuilder();
		DownLoadPicInfo.Builder listBkInfo = DownLoadPicInfo.newBuilder();
		// 非一级页面标题背景
		DownLoadPicInfo.Builder secTitleIconBkInfo = DownLoadPicInfo
				.newBuilder();
		secTitleIconBkInfo.setPicName(TITLE_BK_IMG_HOME_NAME);
		String subTitleBGUrl = getBkUrl(styleId,
				appUpdateTab.getIntAppSecondTitleImgId(),
				GenericConstants.STYLE_TYPE_TITLE, appUpdateTab);
		if (StringUtils.isBlank(subTitleBGUrl)) {
			// 如果二级没有上传图片默认使用第一级的
			subTitleBGUrl = getBkUrl(styleId,
					appUpdateTab.getIntAppTitleBgImgId(),
					GenericConstants.STYLE_TYPE_TITLE, appUpdateTab);
		}
		secTitleIconBkInfo.setPicUrl(subTitleBGUrl);
		// list背景
		listBkInfo.setPicName(LIST_BK_IMG_NAME);
		listBkInfo.setPicUrl(getBkUrl(styleId, 0,
				GenericConstants.STYLE_TYPE_LIST, appUpdateTab));
		// 导航图标点击效果
		DownLoadPicInfo.Builder navIconBkInfo = DownLoadPicInfo.newBuilder();
		navIconBkInfo.setPicName(NAV_ICON_BK_IMG_NAME);
		navIconBkInfo.setPicUrl(getBkUrl(styleId,
				appUpdateTab.getIntNavBgImgId(),
				GenericConstants.STYLE_TYPE_PRESS, appUpdateTab));

		appBkInfo.setPicName(APP_BK_IMG_NAME);
		appBkInfo.setPicUrl(getBkUrl(styleId,
				appUpdateTab.getIntAppBackgImgId(),
				GenericConstants.STYLE_TYPE_APP_BackGROUND, appUpdateTab));
		titleBkInfo.setPicName(TITLE_BK_IMG_NAME);
		titleBkInfo.setPicUrl(getBkUrl(styleId,
				appUpdateTab.getIntAppTitleBgImgId(),
				GenericConstants.STYLE_TYPE_TITLE, appUpdateTab));
		navBkInfo.setPicName(NAV_BK_IMG_NAME);
		navBkInfo.setPicUrl(getBkUrl(styleId,
				appUpdateTab.getIntAppNavigateBgImgId(),
				GenericConstants.STYLE_TYPE_NAV, appUpdateTab));

		builder.addDownLoadPicInfos(loadingIconInfo);
		builder.addDownLoadPicInfos(logoInfo);
		builder.addDownLoadPicInfos(appBkInfo);
		builder.addDownLoadPicInfos(titleBkInfo);
		builder.addDownLoadPicInfos(navBkInfo);
		builder.addDownLoadPicInfos(navIconBkInfo);
		builder.addDownLoadPicInfos(secTitleIconBkInfo);
		builder.addDownLoadPicInfos(listBkInfo);

		// 封裝其他打包資源
		populatePackResource(appTab.getVarPackResource(), builder, serverUrl);

		iniCoreInfoBuilder.setAppId(appId);
		iniCoreInfoBuilder.setEnterpriseId(enterpId);
		iniCoreInfoBuilder.setAppIosType(osType);
		iniCoreInfoBuilder.setAppVersion(appVersion);
		iniCoreInfoBuilder.setStyleId(appTab.getIntAppStyleId());
		iniCoreInfoBuilder
				.setGoogleAnalytics(appTab.getVarCountData() == null ? ""
						: appTab.getVarCountData());// 谷歌统计
		// ios证书文件信息
		String varAppstoreCerUrl = appTab.getVarAppstoreCerUrl();
		String varGotoappCerUrl = appTab.getVarGotoappCerUrl();
		if (!StringUtils.isBlank(varAppstoreCerUrl)) {
			String[] urls = StringUtils.split(varAppstoreCerUrl, ";");
			iniCoreInfoBuilder.addCertification(serverUrl + urls[0]);
			iniCoreInfoBuilder.addCertification(serverUrl + urls[1]);
		}
		if (!StringUtils.isBlank(varGotoappCerUrl)) {
			String[] urls = StringUtils.split(varGotoappCerUrl, ";");
			iniCoreInfoBuilder.addCertification(serverUrl + urls[0]);
			iniCoreInfoBuilder.addCertification(serverUrl + urls[1]);
		}
		builder.setIniCoreInfo(iniCoreInfoBuilder);

		List<PageNavigationIconDto> lst = pageNavigationIconDao
				.getNavigationIconByAppId(appId);
		StringBuffer pageList = new StringBuffer();
		int size = lst.size();
		for (int i = 0; i < size; i++) {
			PageNavigationIconDto o = lst.get(i);
			String pageName = "page_" + o.getINT_NAVIGATE_ORDER();
			String pageValue = pageName + ".png," + o.getVAR_NAVIGATE_NAME()
					+ "," + o.getINT_RESOURCE_ID() + "," + (i == 0 ? "1" : "0")
					+ "," + o.getINT_NAVIGATE_TYPE();
			pageList.append(pageName + ",");
			PageInfo.Builder pageInfo = PageInfo.newBuilder();
			pageInfo.setPageInfoName(pageName);
			pageInfo.setPageInfoValue(pageValue);
			DownLoadPicInfo.Builder downLoadPicInfo = DownLoadPicInfo
					.newBuilder();
			downLoadPicInfo.setPicName(pageName + ".png");
			downLoadPicInfo.setPicUrl(o.getVAR_ICON_URL() == null ? "" : o
					.getVAR_ICON_URL());
			guideBarInfoBuilder.addPageInfos(pageInfo);
			builder.addDownLoadPicInfos(downLoadPicInfo);
		}
		guideBarInfoBuilder.setNavigateStyleId(appTab.getIntNavigatestyleId());
		log.info("导航类型：" + appTab.getIntNavigatestyleId());
		guideBarInfoBuilder.setPageList(pageList.substring(0,
				pageList.length() - 1));
		builder.setGuideBarInfo(guideBarInfoBuilder);

		log.info("开始获取系统配置");
		List<AppConfigs> appConfigs = appConfigsDao
				.getConfigs(GenericConstants.APP_ID_PRE + appId);
		if (appConfigs != null && appConfigs.size() != 0) {
			for (AppConfigs appConfig : appConfigs) {
				BuildAppConfigs.Builder buildAppConfig = BuildAppConfigs
						.newBuilder();
				if (appConfig.getKey() != null && appConfig.getValue() != null) {
					buildAppConfig.setKey(appConfig.getKey());
					buildAppConfig.setValue(appConfig.getValue());
					builder.addBuildAppConfigs(buildAppConfig);
					log.info("系统配置 键:" + appConfig.getKey() + " 值:"
							+ appConfig.getValue() + " 分组:"
							+ appConfig.getType());
				}
			}
		}
		log.info("获取系统配置结束");

		log.info("获取打包信息结束");
		return builder.build().toByteArray();
	}

	private void populatePackResource(String resource,
			GetPackInfoSC.Builder builder, String serverUrl) {
		if (!StringUtil.isBlank(resource)) {
			JSONArray ja = JSONArray.fromObject(resource);
			JSONObject obj = null;
			JSONArray data = null;
			for (Object object : ja) {
				obj = JSONObject.fromObject(object);
				data = JSONArray.fromObject(obj.get("data"));
				for (Object object2 : data) {
					obj = JSONObject.fromObject(object2);
					DownLoadPicInfo.Builder packImg = DownLoadPicInfo
							.newBuilder();
					packImg.setPicName(obj.getString("resourceName"));
					packImg.setPicUrl(serverUrl
							+ appIconDao.get(obj.getInt("iconId"))
									.getVarIconUrl());
					builder.addDownLoadPicInfos(packImg);
				}
			}
		}
	}

	private String getBkUrl(int styleId, Integer iconId, int type,
			AppUpdateTab appUpdateTab) {
		String serverUrl = EhCacheManager.getObject(
				GenericConstants.SERVER_URL_PREFIX).toString();
		if (iconId != null && iconId > 0) {
			// 自定义风格
			AppIconTab appBkIcon = appIconDao.get(iconId);
			if (appBkIcon != null) {
				return (appBkIcon.getVarIconUrl() == null ? "" : serverUrl
						+ appBkIcon.getVarIconUrl());
			} else {
				return "";
			}
		} else if (styleId != 0) {
			// 系统风格
			AppStyleImgTab bkStyleImg = appStyleImgDao.getStyleImgById(styleId,
					type);
			if (bkStyleImg == null) {
				return "";
			} else {
				return (bkStyleImg.getVarAppStyleImgUrl() == null ? ""
						: bkStyleImg.getVarAppStyleImgUrl());
			}
		}
		return "";
	}

	@Override
	public int creatComplieTask(Integer appUpdateId, Integer osType,
			String appSign, String appName, double appVersion, Integer styleId)
			throws InvalidProtocolBufferException {
		log.info("创建编译任务开始");
		log.info("appUpdateId:" + appUpdateId + ",osType:" + osType
				+ ",appSign:" + appSign + ",appName:" + appName
				+ ",appVersion:" + appVersion + ",styleId:" + styleId
				+ ",strVersion:" + String.valueOf(appVersion));
		Client c = Client.create();
		CreatComplieTaskCS.Builder builder = CreatComplieTaskCS.newBuilder();
		builder.setAppUpdateId(appUpdateId);
		builder.setOsType(osType);
		builder.setAppSign(appSign);
		builder.setAppName(appName);
		builder.setAppVersion(String.valueOf(appVersion));
		builder.setStyleId(styleId);
		CreatComplieTaskCS cs = builder.build();
		byte[] buffer = cs.toByteArray();
		// char[] send = Base64Coder.encode(buffer);
		// String reqStr = new String(send);
		String reqStr = Conversion.bytesToHexString(buffer);
		String url = EhCacheManager.getObject(
				GenericConstants.DISPATCH_SERVER_URL).toString()
				+ "/resources/rest?cmd="
				+ Cmd.CreatComplieTask.getNumber()
				+ "&data=" + reqStr;
		WebResource r = c.resource(url);
		ClientResponse response = r.get(ClientResponse.class);
		log.info("请求状态码：" + response.getStatus());
		byte[] resData = response.getEntity(byte[].class);
		CreatComplieTaskSC sc = CreatComplieTaskSC.parseFrom(resData);
		c.destroy();
		response.close();
		log.info("创建编译任务结束");
		return sc.getOpCode();
	}

	@Override
	public QryFinishComplieTaskSC qryComplieTask(Integer appUpdateId)
			throws InvalidProtocolBufferException {
		log.info("查询编译任务开始");
		Client c = Client.create();
		QryFinishComplieTaskCS.Builder builder = QryFinishComplieTaskCS
				.newBuilder();
		builder.setAppUpdateId(appUpdateId);
		QryFinishComplieTaskCS cs = builder.build();
		byte[] buffer = cs.toByteArray();
		// char[] send = Base64Coder.encode(buffer);
		// String reqStr = new String(send);
		String reqStr = Conversion.bytesToHexString(buffer);
		String url = EhCacheManager.getObject(
				GenericConstants.DISPATCH_SERVER_URL).toString()
				+ "/resources/rest?cmd="
				+ Cmd.QryFinishComplieTask.getNumber()
				+ "&data=" + reqStr;
		WebResource r = c.resource(url);
		ClientResponse response = r.get(ClientResponse.class);
		log.info("请求状态码：" + response.getStatus());
		byte[] resData = response.getEntity(byte[].class);
		QryFinishComplieTaskSC sc = QryFinishComplieTaskSC.parseFrom(resData);
		c.destroy();
		log.info("查询编译任务结束");
		return sc;
	}

}
